<template>
  <view class="container">
    <image :src="imageUrl" mode="aspectFit" v-if="imageUrl" class="show-image" />
    <button @click="chooseAndPreviewImage">选择图片显示</button>
    <button @click="previewImage" v-if="imageUrl">预览图片</button>
    <image :src="downloadedImage" mode="aspectFit" v-if="downloadedImage" class="show-image" />
    <button @click="downloadImage">获取图片信息</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      imageUrl: '',
      tempImagePath: '',

      downloadedImage: ''  // 存储下载后的网络图片地址
    }
  },
  methods: {
    // 选择本地图片并显示
    chooseAndPreviewImage() {
      uni.chooseImage({
        count: 1, // 选择1张图片
        sourceType: ['album', 'camera'],
        success: (res) => {
          this.tempImagePath = res.tempFilePaths[0]
          this.imageUrl = res.tempFilePaths[0]
        }
      })
    },
    
    // 预览本地图片
    previewImage() {
      if (this.tempImagePath) {
        uni.previewImage({
          current: this.tempImagePath,
          urls: [this.tempImagePath]
        })
      } else {
        uni.showToast({
          title: '请先选择图片',
          icon: 'none'
        })
      }
    },
    
    // 下载网络图片并显示
    downloadImage() {
      const imageUrl = 'https://cdn.pixabay.com/photo/2025/11/05/20/57/monastery-9939590_1280.jpg'
      uni.downloadFile({
        url: imageUrl,
        success: (downloadRes) => {
          if (downloadRes.statusCode === 200) {
            this.downloadedImage = downloadRes.tempFilePath
            console.log('图片下载完成，路径：', downloadRes.tempFilePath)
          }
        },
        progress: (progressRes) => {
          console.log('下载进度：', progressRes.progress, '%')
        },
        fail: (err) => {
          console.error('图片下载失败：', err)
          uni.showToast({
            title: '图片下载失败',
            icon: 'none'
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 50rpx;
}

.show-image {
  width: 300rpx;
  height: 300rpx;
  margin-bottom: 30rpx;
  border: 1px solid #eee; 
}

button {
  margin-bottom: 30rpx;
  width: 600rpx;
}
</style>